import { Response } from 'express'
import { Note } from '../models/Note'
import { AuthRequest } from '../types'

export const getNotes = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const userId = req.user?.id
    const { page = 1, limit = 10, search, tags } = req.query

    const query: any = { userId }

    // 搜索功能
    if (search) {
      query.$or = [
        { title: { $regex: search, $options: 'i' } },
        { content: { $regex: search, $options: 'i' } }
      ]
    }

    // 标签筛选
    if (tags) {
      const tagArray = Array.isArray(tags) ? tags : [tags]
      query.tags = { $in: tagArray }
    }

    const pageNum = parseInt(page as string)
    const limitNum = parseInt(limit as string)
    const skip = (pageNum - 1) * limitNum

    const notes = await Note.find(query)
      .sort({ updatedAt: -1 })
      .skip(skip)
      .limit(limitNum)

    const total = await Note.countDocuments(query)

    res.json({
      success: true,
      data: {
        notes,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total,
          pages: Math.ceil(total / limitNum)
        }
      }
    })
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取笔记列表失败',
      error: (error as Error).message
    })
  }
}

export const getNoteById = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const { id } = req.params
    const userId = req.user?.id

    const note = await Note.findOne({ _id: id, userId })

    if (!note) {
      res.status(404).json({
        success: false,
        message: '笔记不存在'
      })
      return
    }

    res.json({
      success: true,
      data: { note }
    })
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取笔记失败',
      error: (error as Error).message
    })
  }
}

export const createNote = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const { title, content, tags, isPublic } = req.body
    const userId = req.user?.id

    const note = new Note({
      userId,
      title,
      content,
      tags: tags || [],
      isPublic: isPublic || false
    })

    await note.save()

    res.status(201).json({
      success: true,
      message: '笔记创建成功',
      data: { note }
    })
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '创建笔记失败',
      error: (error as Error).message
    })
  }
}

export const updateNote = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const { id } = req.params
    const { title, content, tags, isPublic } = req.body
    const userId = req.user?.id

    const note = await Note.findOneAndUpdate(
      { _id: id, userId },
      { 
        title, 
        content, 
        tags: tags || [], 
        isPublic: isPublic || false,
        updatedAt: new Date()
      },
      { new: true, runValidators: true }
    )

    if (!note) {
      res.status(404).json({
        success: false,
        message: '笔记不存在'
      })
      return
    }

    res.json({
      success: true,
      message: '笔记更新成功',
      data: { note }
    })
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新笔记失败',
      error: (error as Error).message
    })
  }
}

export const deleteNote = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const { id } = req.params
    const userId = req.user?.id

    const note = await Note.findOneAndDelete({ _id: id, userId })

    if (!note) {
      res.status(404).json({
        success: false,
        message: '笔记不存在'
      })
      return
    }

    res.json({
      success: true,
      message: '笔记删除成功'
    })
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除笔记失败',
      error: (error as Error).message
    })
  }
}

export const searchNotes = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const userId = req.user?.id
    const { q } = req.query

    if (!q) {
      res.status(400).json({
        success: false,
        message: '搜索关键词不能为空'
      })
      return
    }

    const notes = await Note.find({
      userId,
      $or: [
        { title: { $regex: q, $options: 'i' } },
        { content: { $regex: q, $options: 'i' } },
        { tags: { $regex: q, $options: 'i' } }
      ]
    }).sort({ updatedAt: -1 })

    res.json({
      success: true,
      data: { notes }
    })
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '搜索笔记失败',
      error: (error as Error).message
    })
  }
}

export const getTags = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const userId = req.user?.id

    const tags = await Note.aggregate([
      { $match: { userId } },
      { $unwind: '$tags' },
      { $group: { _id: '$tags', count: { $sum: 1 } } },
      { $sort: { count: -1 } }
    ])

    res.json({
      success: true,
      data: { tags: tags.map(tag => ({ name: tag._id, count: tag.count })) }
    })
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取标签失败',
      error: (error as Error).message
    })
  }
}